package com.dtx.csnotes.stack;


import java.util.Iterator;

/**
 * 有错误，需要修改的类
 * @param <Item>
 */
public class ArrayStack<Item> implements MyStack<Item> {

    //栈元素数组，只能通过转型来创建泛型数组
    private Object[] array =  new Object[4];

    //元素数量
    private int N = 0;

    @Override
    public MyStack<Item> push(Item item) {
        check();
        array[N++] = item;
        return this;
    }

    @Override
    public Item pop() throws Exception {

        if (isEmpty()) {
            throw new Exception("stack is empty");
        }
        Item item = (Item) array[--N];

        check();

        //避免对象游离
        array[N] = null;

        return item;
    }

    private void check(){
        if (N>=array.length) {
            resize( array.length << 1);
        } else if(N > 0 && N <= array.length >> 2){
            resize(array.length >> 1);
        }
    }

    /**
     * 调整数组大小，使得栈具有伸缩性
     * @return
     */
    private void resize(int size){

        Item[] temp = (Item[]) new Object[size];

        for (int i = 0; i < N; i++) {
            temp[i] = (Item) array[i];
        }
        array = temp;
    }

    @Override
    public boolean isEmpty() {
        return N == 0;
    }

    @Override
    public int size() {
        return N;
    }

    @Override
    public Iterator<Item> iterator() {

        // 返回逆序遍历的迭代器

        return new Iterator<Item>() {

            private int i = N;
            @Override
            public boolean hasNext() {
                return i > 0;
            }

            @Override
            public Item next() {
                return (Item) array[--i];
            }
        };
    }
}
